package com.ruoyi.web.controller.assets;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.system.domain.OliveAssets;
import com.ruoyi.system.domain.ScrapLog;
import com.ruoyi.system.service.IOliveAssetsService;
import com.ruoyi.system.service.IScrapLogService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ScrapAudit;
import com.ruoyi.system.service.IScrapAuditService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 资产报废审核Controller
 * 
 * @author hzl
 * @date 2025-03-24
 */
@RestController
@RequestMapping("/assets/scrapAudit")
public class ScrapAuditController extends BaseController
{
    @Autowired
    private IScrapAuditService scrapAuditService;
    @Autowired
    private IOliveAssetsService oliveAssetsService;
    @Autowired
    private IScrapLogService scrapLogService;

    /**
     * 查询资产报废审核列表
     */
    @PreAuthorize("@ss.hasPermi('assets:scrapAudit:list')")
    @GetMapping("/list")
    public TableDataInfo list(ScrapAudit scrapAudit)
    {
        startPage();
        List<ScrapAudit> list = scrapAuditService.selectScrapAuditList(scrapAudit);
        return getDataTable(list);
    }

    /**
     * 导出资产报废审核列表
     */
    @PreAuthorize("@ss.hasPermi('assets:scrapAudit:export')")
    @Log(title = "资产报废审核", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScrapAudit scrapAudit)
    {
        List<ScrapAudit> list = scrapAuditService.selectScrapAuditList(scrapAudit);
        ExcelUtil<ScrapAudit> util = new ExcelUtil<ScrapAudit>(ScrapAudit.class);
        util.exportExcel(response, list, "资产报废审核数据");
    }

    /**
     * 获取资产报废审核详细信息
     */
    @PreAuthorize("@ss.hasPermi('assets:scrapAudit:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(scrapAuditService.selectScrapAuditById(id));
    }

    /**
     * 新增资产报废审核
     */
    @PreAuthorize("@ss.hasPermi('assets:scrapAudit:add')")
    @Log(title = "资产报废审核", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScrapAudit scrapAudit)
    {
        return toAjax(scrapAuditService.insertScrapAudit(scrapAudit));
    }

    /**
     * 修改资产报废审核
     */
    @PreAuthorize("@ss.hasPermi('assets:scrapAudit:edit')")
    @Log(title = "资产报废审核", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScrapAudit scrapAudit)
    {
        return toAjax(scrapAuditService.updateScrapAudit(scrapAudit));
    }

    /**
     * 删除资产报废审核
     */
    @PreAuthorize("@ss.hasPermi('assets:scrapAudit:remove')")
    @Log(title = "资产报废审核", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(scrapAuditService.deleteScrapAuditByIds(ids));
    }

    /**
     * 通过报废请求
     */
    @PreAuthorize("@ss.hasPermi('assets:scrap:approve')")
    @Log(title = "资产报废", businessType = BusinessType.UPDATE)
    @PostMapping("/approve")
    public AjaxResult approveScrap(@RequestBody ScrapAudit scrapAudit) {
        String assetId = scrapAudit.getAssetId();


        // 验证assetId是否为空
        if (assetId == null || assetId.isEmpty()) {
            return AjaxResult.error("资产ID不能为空");
        }

        // 更新资产状态为"已报废"
        OliveAssets asset = new OliveAssets();
        asset.setAssetId(assetId);
        asset.setOriginaletAssetId(assetId);
        asset.setAssetStatus(4L); // 根据实际状态码调整


        int updateResult = oliveAssetsService.updateOliveAssets(asset);
        if (updateResult > 0) {
            // 更新报废审核状态
            scrapAudit.setStatus(1L); // 1表示通过
            scrapAudit.setReviewTime(new Date());
            scrapAudit.setReviewerId(String.valueOf(getUserId())); // 记录审核人ID

            // 更新审核备注（可选）
            // scrapAudit.setReviewRemark("审核通过");

            scrapAuditService.updateScrapAudit(scrapAudit);


            //获取申请人ID
            Long userId = scrapAudit.getUserId();
            //获取申请时间
            Date applyTime = scrapAudit.getApplyTime();
            //获取报废原因
            String scrapReason = scrapAudit.getScrapReason();
            //获取审核人ID
            Long reviewerId = Long.valueOf(scrapAudit.getReviewerId());
            //获取审核时间
            Date reviewTime = scrapAudit.getReviewTime();
            //获取审核备注（可选）
            String reviewRemark = scrapAudit.getReviewRemark();
            //获取状态
            Long status = scrapAudit.getStatus();

            ScrapLog scrapLog = new ScrapLog();
            scrapLog.setAssetId(assetId);
            scrapLog.setUserId(userId);
            scrapLog.setApplyTime(applyTime);
            scrapLog.setScrapReason(scrapReason);
            scrapLog.setReviewerId(reviewerId);
            scrapLog.setReviewTime(reviewTime);
            scrapLog.setReviewRemark(reviewRemark);
            scrapLog.setStatus(status);
            // 插入报废日志
            scrapLogService.insertScrapLog(scrapLog);
            return AjaxResult.success("报废申请审核通过");
        } else {
            return AjaxResult.error("更新资产状态失败");
        }
    }

    /**
     * 拒绝报废请求
     */
    @PreAuthorize("@ss.hasPermi('assets:scrap:reject')")
    @Log(title = "资产报废", businessType = BusinessType.UPDATE)
    @PostMapping("/reject")
    public AjaxResult rejectScrap(@RequestBody ScrapAudit scrapAudit) {
        String assetId = scrapAudit.getAssetId();

        // 验证assetId是否为空
        if (assetId == null || assetId.isEmpty()) {
            return AjaxResult.error("资产ID不能为空");
        }

        // 更新资产状态为"已报废"
        OliveAssets asset = new OliveAssets();
        asset.setAssetId(assetId);
        asset.setOriginaletAssetId(assetId);
        asset.setAssetStatus(0L); // 根据实际状态码调整

        int updateResult = oliveAssetsService.updateOliveAssets(asset);
        if (updateResult > 0) {
            // 更新报废审核状态
            scrapAudit.setStatus(2L); // 2表示拒绝
            scrapAudit.setReviewTime(new Date());
            scrapAudit.setReviewerId(String.valueOf(getUserId())); // 记录审核人ID

            // 更新审核备注（可选）
            // scrapAudit.setReviewRemark("审核通过");

            scrapAuditService.updateScrapAudit(scrapAudit);

            //获取资产ID
            String logAssetId = scrapAudit.getAssetId();
            //获取申请人ID
            Long userId = scrapAudit.getUserId();
            //获取申请时间
            Date applyTime = scrapAudit.getApplyTime();
            //获取报废原因
            String scrapReason = scrapAudit.getScrapReason();
            //获取审核人ID
            Long reviewerId = Long.valueOf(scrapAudit.getReviewerId());
            //获取审核时间
            Date reviewTime = scrapAudit.getReviewTime();
            //获取审核备注（可选）
            String reviewRemark = scrapAudit.getReviewRemark();
            //获取状态
            Long status = scrapAudit.getStatus();
            ScrapLog scrapLog = new ScrapLog();
            scrapLog.setAssetId(assetId);
            scrapLog.setUserId(userId);
            scrapLog.setApplyTime(applyTime);
            scrapLog.setScrapReason(scrapReason);
            scrapLog.setReviewerId(reviewerId);
            scrapLog.setReviewTime(reviewTime);
            scrapLog.setReviewRemark(reviewRemark);
            scrapLog.setStatus(status);

            // 插入报废日志
            scrapLogService.insertScrapLog(scrapLog);

            return AjaxResult.success("报废申请审核通过");
        } else {
            return AjaxResult.error("更新资产状态失败");
        }
    }
}
